/**
 * Created by Liyuliang on 15/6/1.
 *
 */

var CityList = function(cities){
    this.cities = cities;
    this.continents = [];
    this.continentBox = $('#continent_box_test');
    this.cityBox = $('#city_box_test');

    this.btnStart = $('#btn-start-test');
    this.btnEnd = $('#btn-end-test');
    this.btnPass = $('#btn-pass-test');

    //已经选中的城市
    var selected = {
        continent: '亚洲',
        start: null,
        end: null,
        pass: []
    };

    var self = this;

    function _resetContinentBox(){
        self.continentBox.html('');
    }
    function _resetCityBox(){
        self.cityBox.html('');
    }
    function _resetBox(){
        _resetCityBox();
        _resetContinentBox();
    }
    function _resetStartCity(){
        selected.start = null;
    }
    function _resetEndCity(){
        selected.end = null;
    }
    function _resetPassCity(){
        selected.pass = [];
    }
    //获取城市
    function _getCities(continent, type){
        var cities = [];
        for(var key in self.cities){
            if(key == continent){
                var cs = self.cities[key];
                for(var k in cs){
                    if(type == 'start'){
                        if(type == 'start' && cs[k].is_top == 1){
                            cities.push(cs[k]);
                        }
                    }else{
                        if(cs[k].area_id == selected.start.area_id){
                            cities.push(cs[k]);
                        }
                    }
                }
            }
        }
        return cities;
    }
    function groupByPinyin(cities){
        var cs = [];
        for(var i = 65; i < 91; i++) {
            cs[String.fromCharCode(i)] = [];
        }
        for(var i = 0,length = cities.length; i < length; i++){
            var city = cities[i];
            var charAtFirst = city.pinyin_name[0];
            for(var key in cs){
                if(key == charAtFirst.toUpperCase()){
                    cs[key].push(city);
                }
            }
        }
        return cs;
    }
    function _removePassCity(city){
        var temp = [];
        for(var i = 0, length = selected.pass.length; i < length; i++){
            if(selected.pass[i].id != city.id){
                temp.push(selected.pass[i]);
            }
        }
        selected.pass = temp;
        temp = null;
    }

    //创建大洲列表dom
    function createContinentListDom(current){
        _resetContinentBox();
        for(var i = 0, length = self.continents.length; i < length; i++){
            (function(continent){
                var $dom = $('<li' + (current == continent ? ' class="current"' : '') + '>' + continent + '</li>').on('click', function(){
                    $dom.addClass('current').siblings().removeClass('current');
                    selected.continent = continent;
                    _resetStartCity();
                    _resetEndCity();
                    _resetCityBox();
                    _resetPassCity();
                    createCityListDom(_getCities(continent, 'start'), 'start');
                });
                self.continentBox.append($dom);
            })(self.continents[i]);
        }
    }
    //创建城市列表dom
    function createCityListDom(cities, type){
        var groups = groupByPinyin(cities);
        for(var key in groups){
            console.log(key, groups[key]);
            var group = groups[key];
            if(group.length > 0) {
                $('<li class="letter">' + key + '</li>').appendTo(self.cityBox);
                for (var i = 0, length = group.length; i < length; i++) {
                    //console.log(cs[i]);
                    (function (city) {
                        var className = '';
                        if (selected.start && city.id == selected.start.id) {
                            className = ' class="current start"';
                        } else if (selected.end && city.id == selected.end.id) {
                            className = ' class="current end"'
                        }
                        for (var j = 0, len = selected.pass.length; i < len; i++) {
                            if (selected.pass[i].id == city.id) {
                                className = ' class="current"';
                                break;
                            }
                        }
                        var $cityDom = $('<li' + className + '>' + city.city_name + '</li>');
                        $cityDom.on('click', function () {
                            if (type == 'start' || type == 'end') {
                                if (type == 'start') {
                                    $cityDom.addClass('current start').siblings().removeClass('current');
                                    selected.start = city;
                                } else if (type == 'end') {
                                    $cityDom.addClass('current end').siblings('li:not(.start)').removeClass('current');
                                    selected.end = city;
                                }
                            } else {
                                if ($cityDom.hasClass('start') || $cityDom.hasClass('end')) {
                                    return false;
                                } else if ($cityDom.hasClass('current')) {
                                    $cityDom.removeClass('current');
                                    //TODO remove from selected
                                    _removePassCity(city);
                                } else {
                                    $cityDom.addClass('current');
                                    //TODO add to selected
                                    selected.pass.push(city);
                                }
                            }
                            showResult();
                        });
                        self.cityBox.append($cityDom);
                    })(group[i]);
                }
            }
        }
    }

    function selectStart(){
        var continent = selected.continent;
        var cityList = _getCities(continent, 'start');
        _resetEndCity();
        _resetPassCity();
        _resetBox();
        createContinentListDom(continent);
        createCityListDom(cityList, 'start');
    }
    function selectEnd(){
        if(!selected.start) {
            alert('请选择开始城市');
            return false;
        }
        var continent = selected.continent;
        var cityList = _getCities(continent, 'end');
        _resetPassCity();
        _resetBox();
        createCityListDom(cityList, 'end');
    }
    function selectPass(){
        if(!selected.start || !selected.end) {
            alert('请选择开始、结束城市');
            return false;
        }
        var continent = selected.continent;
        _resetBox();
        createCityListDom(_getCities(continent, 'pass'), 'pass');
    }

    function showResult(){
        var pass = [];
        for(var i = 0, length = selected.pass.length; i < length; i++){
            pass.push(selected.pass[i].city_name);
        }
        $('#result_box').html(
            '开始：' + (selected.start == null ? '' : selected.start.city_name)
        + ' <br />结束：' + (selected.end == null ? '' : selected.end.city_name)
        + '<br />经过：' + pass.join(' '));
    }

    this.init = function(){
        for(var key in self.cities){
            self.continents.push(key);
        }

        self.btnStart.click(function(){
            selectStart();
        });
        self.btnEnd.click(function(){
            selectEnd();
        });
        self.btnPass.click(function(){
            selectPass();
        });

        groupByPinyin([]);
    };
};